﻿#ifndef PLCWRITETHREAD_H
#define PLCWRITETHREAD_H

#include <QThread>
#include <QSemaphore>
#include <QVector>
#include <QString>
#include <QMutex>
#include <QQueue>
#include <QWaitCondition>
#include <QMap>
#include <QVariant>
#include "open62541.h"

class PLCCommOPCUA;

struct Task {
    enum Type {
        WriteValveStatus,
        WriteAllValveStatus,
        WriteFlowRate,
        WriteAllFlowRate,
        WritePressure,
        WriteAllPressure,
        WriteMKS,
        WriteTemperature,
        WriteDataFromHomePage
    };

    Type type;
    QString endpointUrl;
    int channel;
    bool boolValue;
    int16_t int16Value;
    QVector<bool> boolVector;
    QVector<int16_t> int16Vector;
    QVector<int16_t> int16Vector2;
    int16_t mksPressure;
    int16_t mksOpening;
    int16_t mksMode;
    bool tempStatus1;
    bool tempStatus2;
    int16_t temp1;
    int16_t temp2;
};

class PLCWriteThread : public QThread
{
public:
    explicit PLCWriteThread(Open62541* client, PLCCommOPCUA *parent = nullptr);
    void stop();

    void writeValveStatus(int valveChannel, bool status);
    void writeAllValveStatus(const QVector<bool>& status);

    //流量计操作接口
    void writeFlowRate(int flowmeterChannel, int16_t inputValue);
    void writeAllFlowRate(const QVector<int16_t>& inputValue);

    //压力计操作接口
    void writePressure(int pressuremeterChannel, int16_t inputValue);
    void writeAllPressure(const QVector<int16_t>& inputValue);

    //MKS设备操作接口
    void writeMKS(int16_t pressure, int16_t openingAmplitude, int16_t switchMode);

    //温度设备操作接口
    void writeTemperature(bool status1, bool status2, int16_t temperature1, int16_t temperature2);

    //定制型写入接口(HomePage界面使用)
//    void writeDataFromHomePage(const QVector<int16_t>& flowValues, const QVector<int16_t>& pressureValues, const QVector<bool>& valves);

protected:
    void run() override;

private:
    bool m_isRuning = true;

    PLCCommOPCUA * m_pParent;
    QSemaphore m_sem{0};

    Open62541* m_client;          //OPC UA客户端实例
    QQueue<Task> m_tasks;  //任务队列
    QMutex m_mutex_tasks; // 保护 m_tasks
};

#endif // PLCWRITETHREAD_H
